package com.example.controller;

import com.example.common.model.CommonResult;
import com.example.common.utils.CurrentUserUtil;
import com.example.common.utils.JwtUtils;
import com.example.entity.domain.User;
import com.example.entity.dto.LoginUser;
import com.example.entity.vo.UserVo;
import com.example.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: zhuxiaokang
 * @CreateTime: 2025-04-29
 * @Description: 登录
 * @Version: 1.0
 */

@RestController
@RequestMapping("/plat")
public class LoginController {

    @Resource
    private SysUserService userService;



    @RequestMapping("/login")
    public CommonResult<String> login(@RequestBody LoginUser loginUser) {

        User user = userService.queryUser(loginUser.getUsername(), loginUser.getPassword());
        if (user == null){
            return CommonResult.failed("用户名或密码错误");
        }
        // 生成token
        String token = JwtUtils.generateToken(user);
        return CommonResult.success(token);
    }
    
    @RequestMapping("/userInfo")
    public CommonResult<UserVo> userInfo() {
        //从请求头中取出token
        UserVo currentUser = CurrentUserUtil.getCurrentUser();
        return CommonResult.success(currentUser);
    }


    @PostMapping("/logout")
    @Operation(summary = "退出登录")
    public CommonResult<Void> logout() {
        String header = CurrentUserUtil.getRequest().getHeader("Authorization");
        String token = null;
        if (header != null && header.startsWith("Bearer ")) {
            token = header.substring(7);
        }
        JwtUtils.invalidateToken(token);
        return CommonResult.success();
    }

}
